from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
from rest_framework import serializers
from course.models import Course
from clazz.models import Clazz
from student.models import Student
from score.models import Score
from teacher.models import Teacher
from teacher_course_class.models import TeacherCourseClass
from department.models import Department

# Create your views here.

# 课程列表序列化器
class CourseListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Course
        fields = ['id', 'name', 'credit', 'description']

# 课程创建/更新序列化器
class CourseCreateUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Course
        fields = ['id', 'name', 'credit', 'description']

# 班级创建/更新序列化器
class ClassCreateUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Clazz
        fields = ['id', 'name', 'code', 'department']

# 学生创建/更新序列化器
class StudentCreateUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ['id', 'name', 'student_num', 'clazz']

# 课程班级详情序列化器
class CourseClassDetailSerializer(serializers.ModelSerializer):
    department = serializers.CharField(source='department.name', read_only=True)
    teacher = serializers.SerializerMethodField()
    
    class Meta:
        model = Clazz
        fields = ['id', 'name', 'code', 'department', 'teacher']
    
    def get_teacher(self, obj):
        """获取该班级该课程的授课教师"""
        course_id = self.context.get('course_id')
        if course_id:
            try:
                teacher_course_class = TeacherCourseClass.objects.filter(
                    course_id=course_id,
                    clazz=obj
                ).first()
                if teacher_course_class:
                    return teacher_course_class.teacher.name
            except Exception:
                pass
        return ""

# 课程学生详情序列化器
class CourseStudentDetailSerializer(serializers.ModelSerializer):
    score = serializers.SerializerMethodField()
    
    class Meta:
        model = Student
        fields = ['id', 'name', 'student_num', 'score']
    
    def get_score(self, obj):
        """获取学生该课程的成绩"""
        course_id = self.context.get('course_id')
        if course_id:
            try:
                score = Score.objects.filter(
                    student=obj,
                    course_id=course_id
                ).first()
                if score:
                    return score.value
            except Exception:
                pass
        return None

# 课程管理视图
class CourseManagementView(APIView):
    """课程管理相关接口"""
    
    def get(self, request):
        """获取课程列表 - 课程页"""
        try:
            # 获取所有课程
            courses = Course.objects.all()
            
            # 序列化数据
            serializer = CourseListSerializer(courses, many=True)
            
            # 构建响应
            res = {
                'status': 200,
                'data': {
                    'total': courses.count(),
                    'list': serializer.data,
                    'message': '课程列表获取成功'
                }
            }
            return Response(res, status=status.HTTP_200_OK)
            
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'total': 0,
                    'list': [],
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def post(self, request):
        """创建新课程"""
        try:
            serializer = CourseCreateUpdateSerializer(data=request.data)
            if serializer.is_valid():
                course = serializer.save()
                res = {
                    'status': 201,
                    'data': {
                        'id': course.id,
                        'message': '课程创建成功'
                    }
                }
                return Response(res, status=status.HTTP_201_CREATED)
            else:
                res = {
                    'status': 400,
                    'data': {
                        'message': '数据验证失败',
                        'errors': serializer.errors
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def put(self, request, course_id=None):
        """更新课程信息"""
        try:
            if not course_id:
                res = {
                    'status': 400,
                    'data': {
                        'message': '课程ID不能为空'
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
            
            course = Course.objects.filter(id=course_id).first()
            if not course:
                res = {
                    'status': 404,
                    'data': {
                        'message': '课程不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            serializer = CourseCreateUpdateSerializer(course, data=request.data, partial=True)
            if serializer.is_valid():
                serializer.save()
                res = {
                    'status': 200,
                    'data': {
                        'message': '课程更新成功'
                    }
                }
                return Response(res, status=status.HTTP_200_OK)
            else:
                res = {
                    'status': 400,
                    'data': {
                        'message': '数据验证失败',
                        'errors': serializer.errors
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def delete(self, request, course_id=None):
        """删除课程"""
        try:
            if not course_id:
                res = {
                    'status': 400,
                    'data': {
                        'message': '课程ID不能为空'
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
            
            course = Course.objects.filter(id=course_id).first()
            if not course:
                res = {
                    'status': 404,
                    'data': {
                        'message': '课程不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            course.delete()
            res = {
                'status': 200,
                'data': {
                    'message': '课程删除成功'
                }
            }
            return Response(res, status=status.HTTP_200_OK)
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class CourseClassDetailView(APIView):
    """课程班级详情接口"""
    
    def get(self, request, course_id):
        """获取开设某课程的班级列表"""
        try:
            # 验证课程是否存在
            course = Course.objects.filter(id=course_id).first()
            if not course:
                res = {
                    'status': 404,
                    'data': {
                        'total': 0,
                        'list': [],
                        'message': '课程不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            # 获取开设该课程的班级
            # 通过TeacherCourseClass查找有该课程记录的班级
            teacher_course_classes = TeacherCourseClass.objects.filter(course_id=course_id)
            class_ids = teacher_course_classes.values_list('clazz_id', flat=True).distinct()
            
            # 获取班级信息
            classes = Clazz.objects.filter(id__in=class_ids)
            
            # 序列化数据，传递课程ID用于获取教师信息
            serializer = CourseClassDetailSerializer(
                classes, 
                many=True,
                context={'course_id': course_id}
            )
            
            # 构建响应
            res = {
                'status': 200,
                'data': {
                    'total': classes.count(),
                    'list': serializer.data,
                    'message': '班级列表获取成功'
                }
            }
            return Response(res, status=status.HTTP_200_OK)
            
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'total': 0,
                    'list': [],
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def post(self, request, course_id):
        """在课程下新增班级"""
        try:
            # 验证课程是否存在
            course = Course.objects.filter(id=course_id).first()
            if not course:
                res = {
                    'status': 404,
                    'data': {
                        'message': '课程不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            # 创建班级
            serializer = ClassCreateUpdateSerializer(data=request.data)
            if serializer.is_valid():
                clazz = serializer.save()
                
                # 创建班级与课程的关联（通过TeacherCourseClass）
                # 这里需要传入teacher_id，可以从请求中获取或使用默认值
                teacher_id = request.data.get('teacher_id')
                if teacher_id:
                    TeacherCourseClass.objects.create(
                        course=course,
                        clazz=clazz,
                        teacher_id=teacher_id
                    )
                
                res = {
                    'status': 201,
                    'data': {
                        'id': clazz.id,
                        'message': '班级创建成功'
                    }
                }
                return Response(res, status=status.HTTP_201_CREATED)
            else:
                res = {
                    'status': 400,
                    'data': {
                        'message': '数据验证失败',
                        'errors': serializer.errors
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def put(self, request, course_id, class_id=None):
        """更新班级信息"""
        try:
            if not class_id:
                res = {
                    'status': 400,
                    'data': {
                        'message': '班级ID不能为空'
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
            
            # 验证课程和班级是否存在
            course = Course.objects.filter(id=course_id).first()
            if not course:
                res = {
                    'status': 404,
                    'data': {
                        'message': '课程不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            clazz = Clazz.objects.filter(id=class_id).first()
            if not clazz:
                res = {
                    'status': 404,
                    'data': {
                        'message': '班级不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            serializer = ClassCreateUpdateSerializer(clazz, data=request.data, partial=True)
            if serializer.is_valid():
                serializer.save()
                
                # 更新教师关联（如果提供了teacher_id）
                teacher_id = request.data.get('teacher_id')
                if teacher_id:
                    teacher_course_class = TeacherCourseClass.objects.filter(
                        course=course,
                        clazz=clazz
                    ).first()
                    if teacher_course_class:
                        teacher_course_class.teacher_id = teacher_id
                        teacher_course_class.save()
                
                res = {
                    'status': 200,
                    'data': {
                        'message': '班级更新成功'
                    }
                }
                return Response(res, status=status.HTTP_200_OK)
            else:
                res = {
                    'status': 400,
                    'data': {
                        'message': '数据验证失败',
                        'errors': serializer.errors
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def delete(self, request, course_id, class_id=None):
        """删除班级"""
        try:
            if not class_id:
                res = {
                    'status': 400,
                    'data': {
                        'message': '班级ID不能为空'
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
            
            # 验证课程和班级是否存在
            course = Course.objects.filter(id=course_id).first()
            if not course:
                res = {
                    'status': 404,
                    'data': {
                        'message': '课程不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            clazz = Clazz.objects.filter(id=class_id).first()
            if not clazz:
                res = {
                    'status': 404,
                    'data': {
                        'message': '班级不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            # 删除班级与课程的关联
            TeacherCourseClass.objects.filter(course=course, clazz=clazz).delete()
            
            # 删除班级（注意：这会删除班级及其所有学生）
            clazz.delete()
            
            res = {
                'status': 200,
                'data': {
                    'message': '班级删除成功'
                }
            }
            return Response(res, status=status.HTTP_200_OK)
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class CourseStudentDetailView(APIView):
    """课程学生详情接口"""
    
    def get(self, request, course_id, class_id):
        """获取某班级某课程的学生成绩列表"""
        try:
            # 验证课程和班级是否存在
            course = Course.objects.filter(id=course_id).first()
            if not course:
                res = {
                    'status': 404,
                    'data': {
                        'total': 0,
                        'list': [],
                        'message': '课程不存在',
                        
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            clazz = Clazz.objects.filter(id=class_id).first()
            if not clazz:
                res = {
                    'status': 404,
                    'data': {
                        'total': 0,
                        'list': [],
                        'message': '班级不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            # 获取该班级的学生
            students = Student.objects.filter(clazz_id=class_id)
            
            # 序列化数据，传递课程ID用于获取成绩信息
            serializer = CourseStudentDetailSerializer(
                students, 
                many=True,
                context={'course_id': course_id}
            )
            
            # 构建响应
            res = {
                'status': 200,
                'data': {
                    'total': students.count(),
                    'list': serializer.data,
                    'message': '学生列表获取成功'
                }
            }
            return Response(res, status=status.HTTP_200_OK)
            
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'total': 0,
                    'list': [],
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def post(self, request, course_id, class_id):
        """在班级和课程下新增学生"""
        try:
            # 验证课程和班级是否存在
            course = Course.objects.filter(id=course_id).first()
            if not course:
                res = {
                    'status': 404,
                    'data': {
                        'message': '课程不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            clazz = Clazz.objects.filter(id=class_id).first()
            if not clazz:
                res = {
                    'status': 404,
                    'data': {
                        'message': '班级不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            # 设置班级ID
            data = request.data.copy()
            data['clazz'] = class_id
            
            # 创建学生
            serializer = StudentCreateUpdateSerializer(data=data)
            if serializer.is_valid():
                student = serializer.save()
                
                # 创建学生成绩记录
                score_value = request.data.get('score')
                if score_value is not None:
                    Score.objects.create(
                        student=student,
                        course=course,
                        value=score_value
                    )
                
                res = {
                    'status': 201,
                    'data': {
                        'id': student.id,
                        'message': '学生创建成功'
                    }
                }
                return Response(res, status=status.HTTP_201_CREATED)
            else:
                res = {
                    'status': 400,
                    'data': {
                        'message': '数据验证失败',
                        'errors': serializer.errors
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def put(self, request, course_id, class_id, student_id=None):
        """更新学生信息"""
        try:
            if not student_id:
                res = {
                    'status': 400,
                    'data': {
                        'message': '学生ID不能为空'
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
            
            # 验证课程、班级和学生是否存在
            course = Course.objects.filter(id=course_id).first()
            if not course:
                res = {
                    'status': 404,
                    'data': {
                        'message': '课程不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            clazz = Clazz.objects.filter(id=class_id).first()
            if not clazz:
                res = {
                    'status': 404,
                    'data': {
                        'message': '班级不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            student = Student.objects.filter(id=student_id).first()
            if not student:
                res = {
                    'status': 404,
                    'data': {
                        'message': '学生不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            # 更新学生信息
            serializer = StudentCreateUpdateSerializer(student, data=request.data, partial=True)
            if serializer.is_valid():
                serializer.save()
                
                # 更新学生成绩
                score_value = request.data.get('score')
                if score_value is not None:
                    score = Score.objects.filter(
                        student=student,
                        course=course
                    ).first()
                    if score:
                        score.value = score_value
                        score.save()
                    else:
                        Score.objects.create(
                            student=student,
                            course=course,
                            value=score_value
                        )
                
                res = {
                    'status': 200,
                    'data': {
                        'message': '学生信息更新成功'
                    }
                }
                return Response(res, status=status.HTTP_200_OK)
            else:
                res = {
                    'status': 400,
                    'data': {
                        'message': '数据验证失败',
                        'errors': serializer.errors
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def delete(self, request, course_id, class_id, student_id=None):
        """删除学生"""
        try:
            if not student_id:
                res = {
                    'status': 400,
                    'data': {
                        'message': '学生ID不能为空'
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
            
            # 验证课程、班级和学生是否存在
            course = Course.objects.filter(id=course_id).first()
            if not course:
                res = {
                    'status': 404,
                    'data': {
                        'message': '课程不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            clazz = Clazz.objects.filter(id=class_id).first()
            if not clazz:
                res = {
                    'status': 404,
                    'data': {
                        'message': '班级不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            student = Student.objects.filter(id=student_id).first()
            if not student:
                res = {
                    'status': 404,
                    'data': {
                        'message': '学生不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            # 删除学生成绩记录
            Score.objects.filter(student=student, course=course).delete()
            
            # 删除学生
            student.delete()
            
            res = {
                'status': 200,
                'data': {
                    'message': '学生删除成功'
                }
            }
            return Response(res, status=status.HTTP_200_OK)
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
